Omits the key-value pairs corresponding to the given keys from an object.
Use Object.keys(obj), Array.prototype.filter() and Array.prototype.includes() to remove the provided keys. Use Array.prototype.reduce() to convert the filtered keys back to an object with the corresponding key-value pairs.
const omit = (obj, arr) =>
Object.keys(obj)
.filter(k => !arr.includes(k))
.reduce((acc, key) => ((acc[key] = obj[key]), acc), {});
EXAMPLES
omit({ a: 1, b: '2', c: 3 }, ['b']);
// { 'a': 1, 'c': 3 }
簡單來講我們要刪除一個物件裡面的值, 使用Object.keys(obj) 和 filter() includes() 刪除我們指定的鍵(key),那再來使用 reduce() 轉換相對應物件的鍵
Object.keys()
var arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']
// 類似陣列的物件
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']
// 擁有隨機 key 排序,類似陣列的物件
var an_obj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(an_obj)); // console: ['2', '7', '100']
1.先選出key
2.使用filter() includes() 刪除我們指定的元素